<template>
  <div class="new-type">
    <SelectType v-model="values"
                class="simple-select"
                @input="handleInput"
                @visibleOff="visibleOff" />
    <el-popover v-model="visible"
                placement="bottom"
                width="236"
                trigger="click">
      <div class="eject-input">
        <el-input v-model="typeName"
                  placeholder="请添加物品类型"
                  maxlength="30"></el-input>
        <el-button :disabled="!typeName"
                   type="primary"
                   @click="insert">确认</el-button>
      </div>
      <i slot="reference"
         class="el-icon-circle-plus"></i>
    </el-popover>
  </div>
</template>

<script>
import SelectType from "./SelectType"
import { goodsType } from "@/api/index";
export default {
  name: "SelectNewType",
  components: { SelectType },
  props: {
    value: [Number, String],
  },
  data () {
    return {
      typeName: "",
      values: null,
      goodsTypeOptions: [], // 物品类型
      visible: false
    }
  },
  watch: {
    visible: {
      handler () {
        this.typeName = ''
      }
    }
  },
  created () {
    this.values = this.value === 'undefined' ? '' : this.value
    this.search()
  },
  methods: {
    handleInput (val) {
      this.$emit("input", val);
    },
    async search () {
      let { data } = await goodsType.search({ size: 1000 })
      this.goodsTypeOptions = data.records
    },
    async insert () {
      if (!this.goodsTypeOptions.filter(item => item.name == this.typeName).length) {
        let { data, code, message } = await goodsType.insert({ name: this.typeName });
        if (code === 0) {
          this.handleInput(data.goodsTypeId);
          this.search()
          this.$message.success(message);
          this.visible = false
        } else {
          this.$message.error(message);
        }
      } else {
        this.$message.warning('已存在物品类型，请去选择');
      }
    },
    visibleOff (val) {
      this.visible = val
    }
  }
}
</script>
<style scoped>
.simple-select {
  display: inline-block;
  width: calc(100% - 20px);
  margin-right: 5px;
}
.simple-select >>> .el-input__inner {
  padding-right: 3px;
}
.simple-select >>> .el-input__suffix-inner i {
  width: 90%;
  text-align: left;
  padding-left: 15px;
}
::v-deep .el-icon-circle-plus {
  width: 0;
  font-size: 23px;
  position: absolute;
  right: 27px;
  top: 14px;
  overflow: visible;
  cursor: pointer;
}
.eject-input {
  display: flex;
  justify-content: space-between;
}
.eject-input >>> .el-input {
  width: 164px;
}
</style>